package com.kuang.pool.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;

/**
 * Created by 郭浩 on 2020/9/23 8:53
 */
public class MyconnectionPool {
    //线程池使用列表的结构来实现
    private static LinkedList<Connection> pool = new LinkedList<>();
    private static Integer initCount = 0;

    //池子一开始就要先创建好，所以需要放在静态代码块里面
    static{
        //将配置文件读成流到类加载器中
        InputStream resourceAsStream = MyconnectionPool.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();

        try {
            properties.load(resourceAsStream);
            //得到相应的值
            String driverClassName = properties.getProperty("driverClassName");
            String url = properties.getProperty("url");
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String initialConnectionCount = properties.getProperty("initialConnectionCount");
            initCount = Integer.parseInt(initialConnectionCount);
            //反射加载静态代码，创建一个Drivermanger
            Class.forName(driverClassName);
            //根据initcount的数量初始化连接池的数量
            for (Integer i = 0; i < initCount; i++) {
                Connection connection = DriverManager.getConnection(url, user, password);
                pool.add(connection);
            }

        } catch (IOException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
    public Connection getConnection(){
        if (pool.size() >= 0.3 * initCount){
            return pool.removeLast();
        }
        return pool.getLast();
    }

    public void returnConnection(Connection connection){
        pool.addFirst(connection);
    }

    private void DynamicExpand() {

    }
}
